package thread;
/** date:2023-2-12
 * 顺序打印-进阶版
 * 有三个线程，分别只能打印 A，B 和 C,要求按顺序打印 ABC，打印 10 次
 */
public class Demo4 {
    // 创建3个锁
    private static Object loker1 = new Object();
    private static Object loker2 = new Object();
    private static Object loker3 = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    synchronized (loker1) {
                        loker1.wait();
                    }
                    System.out.println("A");
                    synchronized (loker2) {
                        loker2.notify();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t2 = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    synchronized (loker2) {
                        loker2.wait();
                    }
                    System.out.println("B");
                    synchronized (loker3) {
                        loker3.notify();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread t3 = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    synchronized (loker3) {
                        loker3.wait();
                    }
                    System.out.println("C");
                    synchronized (loker1) {
                        loker1.notify();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        t1.start();
        t2.start();
        t3.start();

        Thread.sleep(1000); // 为了先让 t1 在阻塞状态中

        synchronized (loker1) {
            loker1.notify(); // 然后此时唤醒正在阻塞的 t1 线程
        }
    }
}
